# coding=utf8
# 全世界最帅的帅哥
from flask_restful import reqparse, Resource
from comment.modules import db
from comment.modules.debt_info import DebtInfo
from .serializer import DebtPaginateSerializer, RepayPlanSerializer
from comment.utils.decorators import login_required
from comment.modules.user import User
from flask import g
from comment.modules.debt_repay import DebtorRepay
from datetime import datetime


class RepayPlan(Resource):
    method_decorators = [login_required]

    def get(self):
        # 查询某个匹配成功的借款所对应的还款计划
        # 管理员查询所有的债券列表
        rp = reqparse.RequestParser()
        rp.add_argument("debtId", required=True)

        args = rp.parse_args()
        debt_id = args.debtId
        repay_list = DebtorRepay.query.filter(DebtorRepay.claimsId == debt_id).all()
        repay_data = RepayPlanSerializer(repay_list).to_dict()

        return {"msg": "查询还款计划成功", "data": repay_data}

    def post(self):
        # 还款到指定的某个还款计划的某一期
        rp = reqparse.RequestParser()
        rp.add_argument("repayId", required=True)
        rp.add_argument("repayAmount", required=True)

        args = rp.parse_args()
        repay_id = args.repayId
        repay_amount = args.repayAmount
        user_id = g.user_id
        user = User.query.filter(User.id == user_id).first()

        # 判断用户的账户余额是否足够还款
        if user.accountInfo.balance < repay_amount:
            return {"message": "可用余额不足", "code": 20005}
        else:
            # 扣除余额
            user.accountInfo.balance = user.accountInfo.balance - repay_amount
            repay = DebtorRepay.query.filter(DebtorRepay.id == repay_id).first()
            # 更改还款状态
            repay.isReturned = 1
            # 记录还款的日期
            repay.recordDate = datetime.now()
            db.session.commit()
            return {"msg": "还款成功"}


class Debt(Resource):
    method_decorators = [login_required]

    def get(self):
        user = User.query.filter(User.id == g.user_id).first()
        if user.role != 1:
            return {"message": "当前用户不是管理员！"}
        # 管理员查询所有的债券列表
        rp = reqparse.RequestParser()
        rp.add_argument("start")  # 开始时间
        rp.add_argument("end")  # 结束时间
        rp.add_argument("curPage")  # 当前页
        rp.add_argument("perPage")

        args = rp.parse_args()
        start = args.start
        end = args.end
        cur_page = args.curPage
        per_page = args.perPage

        # 过滤查询

        debt_query = DebtInfo.query
        # 2.时间
        if start:
            debt_query = debt_query.filter(db.cast(DebtInfo.applyDate, db.DATE) <= db.cast(start, db.DATE))
        if end:
            debt_query = debt_query.filter(db.cast(DebtInfo.applyDate, db.DATE) <= db.cast(end, db.DATE))
        debt_paginate = debt_query.paginate(page=cur_page, per_page=per_page, error_out=False)
        loan_data = DebtPaginateSerializer(debt_paginate).to_dict()
        return {"msg": "查询借款数据成功", "data": loan_data}
